package cn.zhangfusheng.elasticsearch.dynamic;

import cn.zhangfusheng.elasticsearch.constant.enumeration.DyanmicType;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * @author fusheng.zhang
 * @date 2022-06-20 16:04:40
 */
@Data
@AllArgsConstructor
public class DyanmicExecuteResult {

    private DyanmicType type;

    private StringBuilder strResult;

    private List<Object> args;

    /**
     * 替换 字符串中的占位符
     * @return
     */
    public String getStrResult() {
        String str = this.strResult.toString();
        Iterator<Object> iterator = this.getArgs().iterator();
        while (str.contains("?")) {
            Object o = iterator.hasNext() ? iterator.next() : "";
            if (Objects.equals(type, DyanmicType.SQL) && o instanceof String) o = String.format("'%s'", o);
            str = str.replaceFirst("\\?", String.valueOf(o));
        }
        return str;
    }

}
